import Vue from 'vue'
import Router from 'vue-router'
import http from '../http.js'
import cookie from 'vue-cookie'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '../store.js'

Vue.use(Router)

const routes = new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      meta: {
        title: '首页'
      },
      component: (resolve) => require(['@/views/index.vue'], resolve)
    }
  ]
})

const title = document.title

routes.beforeEach((to, form, next) => {
  nprogress.start()
  let tok = cookie.get('login_token')
  if (tok === null) {
    http.get('auth/check')
      .catch((result) => {
        if (result.response.status === 401) {
          location.href = result.response.data.url
        }
      })
  } else {
    if (store.getters.menu === null) {
      store.dispatch('getMenu')
        .then(() => {
          let list = store.getters.menu
          for (let i = 0; i < list.length; i++) {
            list[i].component = (resolve) => require(['@/views/' + list[i].name + '.vue'], resolve)
          }
          list.push({
            path: '*',
            name: '404',
            component: (resolve) => require(['@/views/404.vue'], resolve)
          })
          routes.addRoutes(list)
        })
    }
  }
  document.title = title + ' - ' + to.meta.title
  next()
})

routes.afterEach(() => {
  nprogress.done()
})

export default routes
